package hk.m4s.lr.repair.test.ui.user;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.ObjectConstructor;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import framework.common.Constant;
import framework.common.baseui.UeBaseActivity;
import framework.common.cache.CacheData;
import framework.common.cache.CacheManager;
import framework.common.cache.CacheUtils;
import framework.common.kankan.wheel.widget.OnWheelChangedListener;
import framework.common.kankan.wheel.widget.WheelView;
import framework.common.kankan.wheel.widget.adapters.ArrayWheelAdapter;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.FileUtil;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.model.AddressModel;
import hk.m4s.lr.repair.test.model.CityModel;
import hk.m4s.lr.repair.test.model.DistrictModel;
import hk.m4s.lr.repair.test.model.ProvinceModel;
import hk.m4s.lr.repair.test.service.address.AddressService;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import okhttp3.Response;

/***
 * 添加收货地址
 **/
public class AddAddressActivity extends UeBaseActivity implements View.OnClickListener, OnWheelChangedListener {
    private Context context;
    private Button show_comfirm;
    private ListView shop_listView;
    private ProgressDialog progress;
    private ImageView check_address;
    private TextView title;
    private EditText add_user, add_phone, add_address;
    private RelativeLayout select_province;
    private TextView add_pro;
    private String checked = "1";
    private String username;
    private String phone;
    private String address;
    private String pro;
    private String states;
    private String province_key;
    private String city_key;
    private String area_key;
    private String state = "2";
    private RelativeLayout select_pro;//选择省市区
    private Button btn_confirm, btn_canle;
    private WheelView mViewProvince;//省
    private WheelView mViewCity;//市
    private WheelView mViewDistrict;//区
    protected String[] mProvinceDatas;
    protected String[] mProvinceIds;
    protected Map<String, String[]> mCitisIdsMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();
    protected Map<String, String[]> mDistrictDatasIdMap = new HashMap<String, String[]>();
    protected String mCurrentProviceName;
    protected String mCurrentCityName;
    private Gson mGson;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName = "";
    protected String mProvinceId = "";
    protected String mCurrentCityID = "";
    protected String mCurrentDistrictID = "";
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private List<CityModel> cityList;
    private List<ProvinceModel> proList;
    private List<DistrictModel> disList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        mGson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .create();
        baseSetContentView(R.layout.activity_add_address);
        hiddenFooter();
        showGoBackBtn();
        String title=getIntent().getStringExtra("title_name");
        if(title!=null){
            setTitleText(title);
        }else{
            setTitleText("添加收货地址");
        }

        initView();
        setUpViews();
    }

    public void initView() {
        show_comfirm = (Button) findViewById(R.id.show_comfirm);
        check_address = (ImageView) findViewById(R.id.check_address);
        //title=(TextView) findViewById(R.id.title);
        add_pro = (TextView) findViewById(R.id.add_province);
        select_province = (RelativeLayout) findViewById(R.id.select_province);
        add_user = (EditText) findViewById(R.id.add_user);
        add_phone = (EditText) findViewById(R.id.add_phone);
        add_address = (EditText) findViewById(R.id.add_address);
        select_pro = (RelativeLayout) findViewById(R.id.select_pro);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        btn_canle = (Button) findViewById(R.id.btn_canle);
        btn_confirm.setOnClickListener(this);
        btn_canle.setOnClickListener(this);
        check_address.setOnClickListener(this);
        show_comfirm.setOnClickListener(this);
        select_province.setOnClickListener(this);
        //title.setText(getIntent().getStringExtra("title_name"));
        username = getIntent().getStringExtra("username");
        phone = getIntent().getStringExtra("phone");
        address = getIntent().getStringExtra("address");
        pro = getIntent().getStringExtra("pro");
        states = getIntent().getStringExtra("state");
        if (username != null) {
            add_user.setText(username);
        }
        if (phone != null) {
            add_phone.setText(phone);
        }
        if (address != null) {
            add_address.setText(address);
        }
        if (states != null) {
            if (states.equals("0")) {
                state = "0";
                checked = "0";
                Drawable rightDrawable = getResources().getDrawable(R.mipmap.select_address_yes);
                check_address.setImageDrawable(rightDrawable);

            } else {
                checked = "1";
                state = "1";
                Drawable rightDrawable = getResources().getDrawable(R.mipmap.select_address_no);
                check_address.setImageDrawable(rightDrawable);
            }
        }
        if (pro != null) {
            add_pro.setText(pro);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.select_province:
                viInput(v);
                show_comfirm.setVisibility(View.GONE);
                select_pro.setVisibility(View.VISIBLE);
                break;
            case R.id.check_address:
                if (checked.equals("0")) {
                    state = "1";
                    checked = "1";
                    Drawable rightDrawable = getResources().getDrawable(R.mipmap.select_address_no);
                    check_address.setImageDrawable(rightDrawable);

                } else {
                    checked = "0";
                    state = "0";
                    Drawable rightDrawable = getResources().getDrawable(R.mipmap.select_address_yes);
                    check_address.setImageDrawable(rightDrawable);
                }
                break;
            case R.id.show_comfirm:
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(getCurrentFocus()
                                        .getWindowToken(),
                                InputMethodManager.HIDE_NOT_ALWAYS);
                if (judNull()) {
                    putAddress(username,phone,address);
                }
                break;
            case R.id.btn_confirm:
                select_pro.setVisibility(View.GONE);
                show_comfirm.setVisibility(View.VISIBLE);
                add_pro.setText(mCurrentProviceName + " " + mCurrentCityName + " " + mCurrentDistrictName);
                break;
            case R.id.btn_canle:
                show_comfirm.setVisibility(View.VISIBLE);
                select_pro.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentDistrictID = mDistrictDatasIdMap.get(mCurrentCityName)[newValue];
        }
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        if (mCitisDatasMap.containsKey(mCurrentProviceName) && mCitisDatasMap.get(mCurrentProviceName).length > 0) {
            mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
            String[] areas = mDistrictDatasMap.get(mCurrentCityName);
            mCurrentCityID = mCitisIdsMap.get(mCurrentProviceName)[pCurrent];
            mCurrentDistrictID = mDistrictDatasIdMap.get(mCurrentCityName)[pCurrent];
            if (areas == null) {
                areas = new String[]{""};
            }
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[pCurrent];
            mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
            mViewDistrict.setCurrentItem(0);
        }
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        mProvinceId = mProvinceIds[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    public boolean judNull() {
        if ((add_user.getText().toString().trim().equals(""))) {
            Toast.makeText(context, "请输入姓名", Toast.LENGTH_SHORT).show();
            return false;
        } else if ((add_phone.getText().toString().trim().equals(""))) {
            Toast.makeText(context, "请输入联系电话", Toast.LENGTH_SHORT).show();
            return false;
        }else if(!FileUtil.isMobileNO(add_phone.getText().toString().trim())){
            Toast.makeText(context, "请输入合法电话号码", Toast.LENGTH_SHORT).show();
            return false;
        } else if ((add_address.getText().toString().trim().equals(""))) {
            Toast.makeText(context, "请输入详细地址", Toast.LENGTH_SHORT).show();
            return false;
        } else if ((add_pro.getText().toString().trim().equals(""))) {
            Toast.makeText(context, "请选择省市区", Toast.LENGTH_SHORT).show();
            return false;
        } else {
            username = add_user.getText().toString().trim();
            phone = add_phone.getText().toString().trim();
            address = add_address.getText().toString().trim();
        }

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    	public void putAddress(final String name,final String phone,final String address) {

				// POST 参数
				Map<String, Object> params = new HashMap<String, Object>();
				try {
                    JSONObject jsondata = new JSONObject();
                    params.put("device_type", Constant.device_type);
                    params.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
                    jsondata.put("name", name);
                    jsondata.put("tel", phone);
                    jsondata.put("address", address);
                    jsondata.put("provinceid", mProvinceId);
                    jsondata.put("cityid", mCurrentCityID);
                    jsondata.put("areaid", mCurrentDistrictID);
                    jsondata.put("state", state);
                    params.put("jsonText", jsondata.toString());
                }catch (JSONException e){
                    e.printStackTrace();
                }
            AddressService.expressAddressAdd(context, params, new ResponseCallback<AddressModel>() {
                @Override
                public void onSuccess(AddressModel addressModel) {
                    ToastUtil.toast(context,"添加成功");
						finish();
                }

                @Override
                public void onError(Response response, int errorCode, String errorMsg, Exception e) {

                }
            });
	}
    public void getPro() {
        cityList = new ArrayList<CityModel>();
        proList = new ArrayList<ProvinceModel>();
        disList = new ArrayList<DistrictModel>();
        CacheData data =  CacheManager.getInstance().getCache(CacheUtils.KEY_TEST);
        if(data!=null) {
            String result = (String) data.getData();
            JSONObject jsonObject = null;
            try {
                if (result == null || "".equals(result)) {
                    return;
                }
                jsonObject = new JSONObject(result);
                JSONObject rep = jsonObject.getJSONObject("data");
                if (jsonObject.get("code").equals("0")) {
                    JSONArray array = rep.getJSONArray("list");
                    mProvinceDatas = new String[array.length()];
                    mProvinceIds = new String[array.length()];
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        mProvinceDatas[i] = obj.getString("province");

                        ProvinceModel bean = new ProvinceModel();
                        bean.setName(obj.getString("province"));
                        if (obj.has("provinceid")) {
                            mProvinceIds[i] = obj.getString("provinceid");
                            bean.setPro_key(obj.getString("provinceid"));
                        }
                        if (obj.has("cities")) {
                            JSONArray ary = obj.getJSONArray("cities");
                            String[] cityNames = new String[ary.length()];
                            String[] cityIds = new String[ary.length()];
                            for (int j = 0; j < ary.length(); j++) {
                                JSONObject cbj = ary.getJSONObject(j);

                                cityNames[j] = cbj.getString("city");
                                cityIds[j] = cbj.getString("cityid");
                                CityModel cb = new CityModel();
                                cb.setName(cbj.getString("city"));
                                cb.setCity_id(cbj.getString("cityid"));
                                cityList.add(cb);
                                if (cbj.has("areas")) {
                                    JSONArray arys = cbj.getJSONArray("areas");
                                    String[] disNames = new String[arys.length()];
                                    String[] disIds = new String[arys.length()];
                                    for (int k = 0; k < arys.length(); k++) {

                                        JSONObject abj = arys.getJSONObject(k);
                                        disNames[k] = abj.getString("area");
                                        disIds[k] = abj.getString("areaid");
                                        DistrictModel model = new DistrictModel();
                                        model.setName(abj.getString("area"));
                                        model.setZipcode(abj.getString("areaid"));
                                        disList.add(model);

                                    }
                                    mDistrictDatasMap.put(cbj.getString("city"), disNames);
                                    mDistrictDatasIdMap.put(cbj.getString("city"), disIds);
                                } else {
                                    String[] disNames = new String[0];
                                    String[] disIds = new String[0];
                                    mDistrictDatasMap.put(cbj.getString("city"), disNames);
                                    mDistrictDatasIdMap.put(cbj.getString("city"), disIds);
                                }

                            }

                            mCitisDatasMap.put(obj.getString("province"), cityNames);
                            mCitisIdsMap.put(obj.getString("province"), cityIds);

                            bean.setCityList(cityList);
                        }
                        proList.add(bean);
                    }
//                if (proList != null && !proList.isEmpty()) {
//                    for (ProvinceModel bean : proList) {
//                        if (bean.getName().equals(
//                                sp.getString("pro")) ){
//                            mCurrentProviceName = bean.getName();
//                            mProvinceId = bean.getPro_key();
//                            List<CityModel> cityLists = bean.getCityList();
//                            for (CityModel be : cityLists) {
//                                if (bean.getName().equals(
//                                        sp.getString("city"))) {
//                                    mCurrentCityName = be.getName();
//                                    mCurrentCityID = be.getCity_id();
//                                }
//                            }
//                        }
//                    }
//
//                }
                    mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(
                            AddAddressActivity.this, mProvinceDatas));
                    // 璁剧疆鍙鏉＄洰鏁伴噺
                    mViewProvince.setVisibleItems(7);
                    mViewCity.setVisibleItems(7);
                    mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AddAddressActivity.this, mProvinceDatas));
                    // 设置可见条目数量
                    mViewProvince.setVisibleItems(7);
                    mViewCity.setVisibleItems(7);
                    mViewDistrict.setVisibleItems(7);
                    updateCities();
                    updateAreas();
                }


            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void setUpViews() {
        mViewProvince = (WheelView) findViewById(R.id.id_provinces);
        mViewCity = (WheelView) findViewById(R.id.id_citys);
        mViewDistrict = (WheelView) findViewById(R.id.id_districts);
        setUpListener();
        setUpData();
    }

    private void setUpData() {
        getPro();

    }

    private void setUpListener() {
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
    }

    public void viInput(View view){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); //强制隐藏键盘
    }
}
